package student;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class StudentDaoImpl implements StudentDao{

	// 先从文件读取，文件没有返回空集合，文件有内容就读取List给它赋值
	List<Student> studentList = FileUtils.readFromFile();
	
	@Override
	public boolean insert(Student student) {
		if (studentList.contains(student)) {
			return false;
		}else {
			return studentList.add(student) && FileUtils.writeToFile(studentList) ;
		}
	}

	@Override
	public boolean deleteById(int id) {
		Student s = new Student();
		s.setId(id);
		// 有就删除成功，成功返回true,失败返回false
		return studentList.remove(s) && FileUtils.writeToFile(studentList);
	}

	@Override
	public boolean update(Student student) {
		int index = studentList.indexOf(student);
		if (index != -1) {
			studentList.set(index, student);
			return FileUtils.writeToFile(studentList);
		}else {
			return false;
		}
	}

	@Override
	public Student selectById(int id) {
		Student s = new Student();
		s.setId(id);
		
		int index = studentList.indexOf(s);
		return index == -1 ? null : studentList.get(index);
	}

	@Override
	public List<Student> selectAll() {
		return studentList;
	}

	@Override
	public List<Student> selectByClass(String className) {
		List<Student> list = new ArrayList<>();
		
		for(Student s : studentList) {
			if (s.getClassName().equals(className)) {
				list.add(s);
			}
		}
		// 判断集合是否为空？ 为空返回空集合而不是null
		return list.isEmpty() ? Collections.emptyList() : list;
	}

	@Override
	public List<Student> orderByScoreDesc() {
		// 所有排序一定拷贝副本，对副本进行排序
		List<Student> newList = new ArrayList<>(studentList);
		newList.sort(new Comparator<Student>() {
			@Override
			public int compare(Student o1, Student o2) {
				return o2.getScore() - o1.getScore();
			}
		});
		return newList;
	}

}
